/* 
 * Copyright 2011 kOSMik.
 * This file is part of kOSMik.
 * 
 * kOSMik is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * kOSMik is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with kOSMik.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * kOSMik:
 * Open Street Map - Editor.
 * http://code.google.com/p/swp-dv-ws2010-osm-2/
 */

package de.fuberlin.kosmik.gui.activity;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import de.fuberlin.kosmik.R;
import de.fuberlin.kosmik.data.DataBaseConnector;
import de.fuberlin.kosmik.data.DataBaseConnectorImpl;
import de.fuberlin.kosmik.files.FileManager;
import de.fuberlin.kosmik.files.FileManagerImpl;
import de.fuberlin.kosmik.files.MediaController;
import de.fuberlin.kosmik.log.Constants;

/**
 * This activity is recording a video and saves them to file system. Puts also
 * an entry to database after saving.
 * 
 * @author Michael Schmidt
 */
public class VideoRecordActivity extends Activity implements OnClickListener,
		SurfaceHolder.Callback {

	/**
	 * Intent param name of track id.
	 */
	public static final String INTENT_PARAM_TRACK_ID = "intent_param_track_id";

	/**
	 * Intent param name of point id, which is associated with the video.
	 */
	public static final String INTENT_PARAM_POINT_ID = "intent_param_point_id";

	/**
	 * Id of the point id, which is associated with the video track.
	 */
	long pointId;

	/**
	 * File object which contains the video file.
	 */
	File file;

	private boolean recording;
	private FileManager fileManager;
	private MediaRecorder mRecorder;
	private Button start_btn;
	private Button end_btn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.video_record);

		Intent intent = this.getIntent();
		pointId = intent.getLongExtra(INTENT_PARAM_POINT_ID, -1);
		long trackId = intent.getLongExtra(INTENT_PARAM_TRACK_ID, -1);
		try {
			fileManager = new FileManagerImpl(trackId);
		} catch (IOException e) {
			Log.d(Constants.TAG, "illegal media state");
			Toast.makeText(this, getString(R.string.err_media_not_ready), Toast.LENGTH_LONG)
					.show();
			this.finish();
		}

		start_btn = (Button) findViewById(R.id.video_start);
		start_btn.setOnClickListener(this);
		end_btn = (Button) findViewById(R.id.video_stop);
		end_btn.setOnClickListener(this);
		end_btn.setEnabled(false);

		recording = false;
		SurfaceView preview = (SurfaceView) findViewById(R.id.video_surface);
		SurfaceHolder holder = preview.getHolder();
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		holder.addCallback(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.video_start && start_btn.isEnabled()) {
			startRecording();
			start_btn.setEnabled(false);
			end_btn.setEnabled(true);
		} else if (v.getId() == R.id.video_stop && end_btn.isEnabled()) {
			stopRecording();
			start_btn.setEnabled(true);
			end_btn.setEnabled(false);
			finish();
		}
	}

	private void startRecording() {
		if (!recording && mRecorder != null) {
			recording = true;
			mRecorder.start();
		}
	}

	private void stopRecording() {
		if (mRecorder != null && recording) {
			mRecorder.stop();
			mRecorder.release();
			recording = false;
			(new Thread(savingHelper)).start();
			Toast.makeText(this, this.getString(R.string.recording_successful),
					Toast.LENGTH_LONG).show();
		}
	}

	private Runnable savingHelper = new Runnable() {
		@Override
		public void run() {
			Log.d(Constants.TAG, "Saving file: " + file.toString() + " at point[id: " + pointId
					+ "]");
			DataBaseConnector db = new DataBaseConnectorImpl(VideoRecordActivity.this);
			db.addMedia(MediaController.MEDIA_TYPE_VIDEO, file.toString(), pointId);
			db.close();
		}
	};

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
			mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
			mRecorder.setMaxDuration(20000);
			mRecorder.setVideoSize(320, 240);
			mRecorder.setVideoFrameRate(15);

			file = new File(fileManager.getAbsoluteBasePath(),
					fileManager.getFilename(MediaController.MEDIA_TYPE_VIDEO) + ".mp4");

			mRecorder.setOutputFile(file.toString());
			mRecorder.setPreviewDisplay(holder.getSurface());
			mRecorder.prepare();

		} catch (IllegalStateException e) {
			Toast.makeText(this, this.getString(R.string.recording_error), Toast.LENGTH_LONG)
					.show();
			mRecorder.release();
			this.finish();
		} catch (IOException e) {
			Toast.makeText(this, this.getString(R.string.recording_error), Toast.LENGTH_LONG)
					.show();
			mRecorder.release();
			this.finish();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		// Do nothing
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		stopRecording();
	}
}
